const { getUserId } = require('../../utils')

const isExist = async (ctx, id) => {
  const exist = await ctx.db.exists.Article({ id })
  if (!exist) {
    throw new Error('did not exist article')
  }
}

const article = {
  async createArticle (parent, { name, subtitle, description, share, sharesIds, cooperations }, ctx, info) {
    const userId = getUserId(ctx)
    const article = await ctx.db.mutation.createArticle(
      {
        data: {
          name,
          subtitle,
          description,
          share,
          owner: {
            connect: { id: userId }
          },
          shares: {
            connect: sharesIds
          },
          cooperations: {
            create: cooperations
          }
        }
      },
      info
    )
    // 发送通知
    if (cooperations && cooperations.length > 0) {
      await cooperations.map(async c => {
        await ctx.db.mutation.createNotice({
          data: {
            content: `邀请加入日记: ${name}`,
            fromUser: {
              connect: {
                id: userId
              }
            },
            toUser: {
              connect: {
                id: c.user.id
              }
            }
          }
        })
      })
    }
    return article
  },
  async updateArticle (parent, { id, name, subtitle, description, share, sharesIds, discooperationUserId, status }, ctx, info) {
    const userId = getUserId(ctx)
    /* const article = await ctx.db.query.article({
      where: {
        id
      }
    })
    if (!article) {
      // 不存在的 ID
    } */
    isExist({ id })
    if (discooperationUserId && article.cooperations.some(c => userId === c.user.id)) {
      // disconnected user 操作
      return ctx.db.mutation.updateArticle({
        where: {
          id
        },
        data: {
          cooperations: {
            disconnect: {
              id: discooperationUserId
            }
          }
        }
      }, info)
    }
    if (article.owner.id === userId) {
      const data = {
        name,
        subtitle,
        description,
        share
      }
      if (sharesIds) {
        // 如果要更改共享列表, 需要先 disconnected 那些已经不存在的, 然后再 connect 那些新增的
        // disconnect, 这里的结构要修改成 id 数组
        const disconnect = article.shares.filter(s => !sharesIds.find(n => n === s.id)).map(s => ({ id: s.id }))
        const connect = sharesIds.filter(s => !article.shares.find(n => n.id === s)).map(s => ({ id: s }))
        data.shares = {
          disconnect,
          connect
        }
      }
      return ctx.db.mutation.updateArticle({
        where: {
          id
        },
        data
      }, info)
    }
  }
}

module.exports = { article }
